package eip.chapter10.processmanager.handler;

import org.apache.log4j.Logger;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import eip.chapter10.processmanager.ScubaDivingBooking;
import eip.chapter10.processmanager.ScubaDivingRequest;
import eip.chapter10.processmanager.TaxiBooking;
import eip.chapter10.processmanager.TaxiRequest;
import eip.util.JibxUtil;

public class TaxiServiceHandler implements ActionHandler {
	
	private static final long serialVersionUID = -2024118944718206007L;
	private final static Logger logger = Logger.getLogger(TaxiServiceHandler.class);
	private String target = "vm://to.taxiService";

	public void execute(ExecutionContext execContext) throws Exception {
		logger.info("entering taxi service handler");
		ScubaDivingRequest bookingRequest = (ScubaDivingRequest) 
				execContext.getContextInstance().getVariable("booking");
		ScubaDivingBooking bookingResponse = (ScubaDivingBooking) 
				execContext.getContextInstance().getVariable("bookingResponse");
		TaxiRequest taxiRequest = new TaxiRequest();
		taxiRequest.setHotelName("SleepingBeauty");
		taxiRequest.setNumberOfTravelers(bookingRequest.getNumberOfDivers());
		taxiRequest.setDepartureTime(bookingResponse.getDivingStartingTime());
		taxiRequest.setReturnTime(bookingResponse.getDivingEndTime());
		taxiRequest.setDestinationAddress(bookingResponse.getSchoolAddress());
		Object responseObject = MuleConnector.invokeRequestResponse(target, JibxUtil.marshall(taxiRequest));
		logger.info("responseObject " + responseObject);
		TaxiBooking taxiBooking = (TaxiBooking) JibxUtil.unmarshall(responseObject.toString(), TaxiBooking.class);
		bookingResponse.setTaxiBookingID(taxiBooking.getTaxiBookingID());
		bookingResponse.setTaxiDepartureTime(taxiBooking.getTaxiDepartureTime());
		bookingResponse.setTaxiReturnTime(taxiBooking.getTaxiReturnTime());
		bookingResponse.setTotalPrice(bookingResponse.getTotalPrice() + taxiBooking.getPrice());
		execContext.leaveNode();
	}
	
}
